package models

import (
	"crypto/md5"
	"encoding/hex"
	"time"

	"github.com/astaxie/beego/orm"
	"github.com/brianvoe/sjwt"
)

type User struct {
	Id            int
	Username      string    `orm:"unique;size(255)" description:"用户名"`
	Password      string    `description:"密码"`
	Openid        string    `description:"用户名"`
	Avatar        string    `description:"头像"`
	LastLoginTime time.Time `orm:"auto_now;type(datetime)" description:"上一次登陆时间"`
	CreateTime    time.Time `orm:"auto_now;auto_now_add;type(datetime)" description:"建立时间"`
	Gender        int       `description:"性别"`
}

func (user *User) SetPassword(password string) {
	newpassword := []byte(password)
	md5Ctx := md5.New()
	md5Ctx.Write(newpassword)
	user.Password = hex.EncodeToString(md5Ctx.Sum(nil))
}

func (user User) CheckPassword(password string) bool {
	newpassword := []byte(password)
	md5C := md5.New()
	md5C.Write(newpassword)
	decodePassword := md5C.Sum(nil)
	encodePassword := hex.EncodeToString(decodePassword)
	if user.Password == encodePassword {
		return true
	}
	return false
}

func (user *User) Jwt() string {
	jwtInstance := sjwt.New()
	jwtInstance.Set("name", user.Username)
	jwtInstance.Set("id", user.Id)
	jwtInstance.Set("avatar", user.Avatar)
	jwtInstance.Set("role", []string{"admin"})
	jwtInstance.Set("LastLoginTime", user.LastLoginTime.String())
	jwtInstance.SetExpiresAt(time.Now().Add(time.Hour * 24))
	secretKey := []byte("secret_xiegao_key")
	jwt := jwtInstance.Generate(secretKey)
	return jwt
}

func init() {
	orm.RegisterModel(new(User))
}
